package tas.co.in.daoimpl.employeeInfo;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import tas.co.in.dao.employeeInfo.EmployeeInfo;
import tas.co.in.domain.customerinfo.CustomerInfoBean;
import tas.co.in.domain.employeeInfo.EmployeeInfoBean;

public class EmployeeInfoImpl extends SqlMapClientDaoSupport implements
		EmployeeInfo {

	TransactionTemplate template = null;

	public void setTemplate(TransactionTemplate template) {
		this.template = template;
	}

	public boolean setEmployeeInfo(final EmployeeInfoBean bean) {

		boolean bool = false;

		bool = (Boolean) template.execute(new TransactionCallback() {

			public Boolean doInTransaction(TransactionStatus status) {

				Object savepoint = null;
				boolean flag = false;

				try {
					CustomerInfoBean bean2 = new CustomerInfoBean();
					CustomerInfoBean infoBean = new CustomerInfoBean();
					CustomerInfoBean infoBean2 = new CustomerInfoBean();
					String customerCode;

					/*
					 * for employee id
					 */
					infoBean.setCode("EMPID");

					bean2 = (CustomerInfoBean) getSqlMapClient()
							.queryForObject("customerInfo.getsystemvalue",
									infoBean);

					infoBean2.setCode("EMPID");

					savepoint = status.createSavepoint();

					if (bean2 == null) {

						infoBean2.setValue(1);

						getSqlMapClient().insert(
								"customerInfo.insertsystemtable", infoBean2);

						customerCode = String.format("%07d", 1);

					} else {

						customerCode = String.format("%07d", bean2.getValue());

						infoBean2.setUpdateValue(bean2.getValue() + 1);

						getSqlMapClient().update(
								"customerInfo.updatesystemtable", infoBean2);

					}

					bean.setEmpID("EMP" + customerCode);

					getSqlMapClient().insert("employeeInfo.setEmployeeRole",
							bean);
					getSqlMapClient().insert(
							"employeeInfo.setEmployeeUserInfo", bean);
					flag = true;
				} catch (Exception e) {

					status.rollbackToSavepoint(savepoint);

					System.out.println(e);
				}
				return flag;
			}

		});

		return bool;
	}

	@SuppressWarnings("unchecked")
	public List<EmployeeInfoBean> getDetails(EmployeeInfoBean bean) {
		try {
			return getSqlMapClient().queryForList(
					"employeeInfo.getEmployeeDetail", bean);
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}

	public boolean updateEmployeeDetail(EmployeeInfoBean bean) {
		boolean flag = false;
		try {
			getSqlMapClient().update("employeeInfo.updatemployeeDetail", bean);
			flag = true;
		} catch (Exception e) {
			System.out.println(e);
		}
		return flag;
	}
}
